/**
 *  author :  tao.zhang
 *  create :  2013-4-11
 */
package edm.qunar.com;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.log4j.Logger;

/**
 * @author tao.zhang
 * 
 */
public class MainController {

	protected static final Logger logger = Logger
			.getLogger(MainController.class.getName());

	private static ConcurrentLinkedQueue<String> urlQueue = new ConcurrentLinkedQueue<String>();

	/**
	 * @param args
	 * @throws EmailException
	 * @throws IOException
	 */
	public static void main(String[] args) {

		String content = "";
		try {
			content = read("test.html");
		} catch (IOException e) {
			logger.error("读取网页模版异常");
			logger.error(e.fillInStackTrace());
			System.exit(1);
		}

		try {
			file2queue("email_list.txt", urlQueue);
		} catch (IOException e) {
			logger.error("读取邮件列表异常");
			logger.error(e.fillInStackTrace());
			System.exit(1);
			;
		}

		EmailConfig cfg = new EmailConfig();

		cfg.setCharset(ConfigUtils.getValue("charset", "utf-8"));
		cfg.setFrom(ConfigUtils.getValue("from", "lvtu@qunar.com"));
		cfg.setHtmlMsg(content);
		cfg.setSubject(ConfigUtils.getValue("subject", ""));
		cfg.setSmtp(ConfigUtils.getValue("smtp", "smtp.qunar.com"));

		logger.info("=====================");
		logger.info("===Qunar edm start=====");
		logger.info("=====================");
		logger.info("邮箱个数：" + urlQueue.size());
		System.out.println(urlQueue);

		// 5 or given
		int workerCount = StringUtils
				.isBlank(JdbcUtils.getThreadCount()) ? 5 : Integer
				.valueOf(JdbcUtils.getThreadCount());
		
		
		long startTime = System.currentTimeMillis();
		ExecutorService exec = Executors.newFixedThreadPool(workerCount);
		for (int i = 0; i < workerCount; i++)
			exec.execute(new EmailWorker(urlQueue, cfg, i));
		exec.shutdown();
		while (true) {
			if (exec.isTerminated()) {
				logger.info("发送邮件共耗时："
						+ (System.currentTimeMillis() - startTime) / 1000
						+ "秒。");
				break;
			}
		}
	}

	// 配置文件读取到String
	private static String read(String filename) throws IOException {
		// Reading input by lines:
		BufferedReader in = new BufferedReader(new FileReader(filename));
		String s;
		StringBuilder sb = new StringBuilder();
		while ((s = in.readLine()) != null)
			sb.append(s + "\n");
		in.close();
		return sb.toString();
	}

	// 配置文件读取到Queue
	private static void file2queue(String filename, Queue<String> q)
			throws IOException {

		// Reading input by lines:
		BufferedReader in = new BufferedReader(new FileReader(filename));
		String s;
		while ((s = in.readLine()) != null)
			// sb.append(s + "\n");
			q.add(s.toString());
		in.close();

	}

}
